package com.dz.lm.service.agentreview.impl;

import com.dz.lm.common.dto.AgentReviewDTO;
import com.dz.lm.common.dto.PageDto;
import com.dz.lm.common.dto.UserProductDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.dao.agentreview.read.AgentReviewDao;
import com.dz.lm.dao.appLogin.read.AppLoginDao;
import com.dz.lm.dao.compproduct.read.CompProductDao;
import com.dz.lm.domain.agentreview.AgentReview;
import com.dz.lm.domain.agentreview.AgentReviewExample;
import com.dz.lm.domain.compproduct.CompProduct;
import com.dz.lm.domain.userapply.UserApply;
import com.dz.lm.domain.usermessage.UserMessage;
import com.dz.lm.domain.userproduct.UserProduct;
import com.dz.lm.service.agentreview.AgentReviewService;
import com.dz.lm.service.product.ProductService;
import com.dz.lm.service.useragent.UserAgentService;
import com.dz.lm.service.usermessage.UserMessageService;
import com.dz.lm.service.userproduct.UserProductService;
import com.github.pagehelper.PageInfo;
import com.smartlbs.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

@Service
public class AgentReviewServiceImpl implements AgentReviewService {
    @Resource(name = "readAgentReviewDao")
    private AgentReviewDao readAgentReviewDao;
    @Resource(name = "writeAgentReviewDao")
    private com.dz.lm.dao.agentreview.write.AgentReviewDao writeAgentReviewDao;
    @Resource(name = "readAppLoginDao")
    private AppLoginDao rAppLoginDao;
    @Autowired
    private UserProductService userProductService;
    @Resource(name = "readCompProductDao")
    private CompProductDao readCompProductDao;
    @Autowired
    private UserMessageService userMessageService;
    @Autowired
    private UserAgentService userAgentService;
    @Override
    public int add(AgentReview agentReview) throws ServiceException {
        return writeAgentReviewDao.insertSelective(agentReview);
    }
    @Transactional
    @Override
    public int doReview(int reviewId, int status, String remark ,String agentContent,double returnPoint ,double agentSale ,String levelNum) throws ServiceException {
        int ret = 0;
        AgentReview agentReview = readAgentReviewDao.selectByPrimaryKey(reviewId);
        AgentReview review = new AgentReview();
        review.setReviewId(reviewId);
        review.setStatus(status);
        review.setRemark(remark);
        if( status == 1 ){ //审核通过推送私信
            UserProductDTO detail = userProductService.getDetail(0, agentReview.getProductId(), false);
            userAgentService.reviewAgent(agentReview.getApplyUid(),agentReview.getHandUid(),1);
            if( !StringUtil.containEmpty(agentContent)){
                UserMessage message = new UserMessage();
                message.setUserId(agentReview.getApplyUid());
                message.setSendUid(detail.getSource());
                message.setMessage(detail.getProductName()+"的代理推送:  "+agentContent);
                message.setCreateTime(com.dz.lm.common.utils.DateUtil.getTimeStr(new Date()));
                userMessageService.add(message);
            }
        }
        try {
            review.setUpdateTime(DateUtil.getNowDateTimeString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        ret = writeAgentReviewDao.updateByPrimaryKeySelective(review);
        if(ret > 0 && status ==1 ){ //审核通过设置产品的返点
            UserProduct product = new UserProduct();
            product.setProductId(agentReview.getApplyPid());
            if(returnPoint > 0){
                product.setReturnPoint(returnPoint);

            }

            if(agentSale > 0){
                product.setAgentSale(agentSale);
            }
            product.setLevelNum(levelNum);
            userProductService.update(product);
        }

        return ret;
    }
    @Transactional
    @Override
    public int delete(int applyPid) throws ServiceException {
        return writeAgentReviewDao.deleteByApplyPid(applyPid);
    }
    @Transactional
    @Override
    public PageDto query(int pageNum, int rows, int handUid, int status) throws ServiceException {
        PageDto pageDto = new PageDto();
        AgentReviewExample ex = new AgentReviewExample();
        ex.setOrderByClause("create_time desc");
        AgentReviewExample.Criteria cr = ex.createCriteria();
        cr.andHandUidEqualTo(handUid);
        cr.andStatusEqualTo(status);
        List<AgentReview> list = readAgentReviewDao.selectByExample(ex);
        if(list != null && list.size() >0){
            PageInfo pageInfo = new PageInfo(list);
            List<AgentReviewDTO> dtos = new ArrayList() ;
            for (AgentReview review : list) {
                AgentReviewDTO dto = new AgentReviewDTO();
                BeanUtils.copyProperties(review,dto);
                try {
                    setExt(dto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dtos.add(dto);
            }
            pageDto.setInfo(pageInfo);
            pageDto.setList(dtos);
        }
        return pageDto;
    }
    private void setExt(AgentReviewDTO dto)throws Exception{
        //申请人
        Map p1 = new HashMap();
        p1.put("userId", dto.getApplyUid());
        Map applyuser = rAppLoginDao.qryUserInfoByUserId(p1);
        if(applyuser != null){
            dto.setApplyUser(applyuser);
        }
        //处理人
        p1.clear();
        p1.put("userId", dto.getHandUid());
        Map handleuser = rAppLoginDao.qryUserInfoByUserId(p1);
        if(handleuser != null){
            dto.setHandUser(handleuser);
        }
        //产品名称
        UserProductDTO deail = userProductService.getDeail(dto.getProductId(), 0);
        if(deail != null){
            dto.setProductName(deail.getProductName());
            dto.setAgentLevel(deail.getAgentLevel());

            if(!StringUtil.containEmpty(deail.getAgentMessage())){
                dto.setAgentMessage(deail.getAgentMessage());
            }
        }
    }
    @Override
    public int queryCount(int handUid, int applyUid,int productId ,int status) throws ServiceException {
        AgentReviewExample ex = new AgentReviewExample();
        AgentReviewExample.Criteria cr = ex.createCriteria();
        if(handUid > 0){
            cr.andHandUidEqualTo(handUid);
        }
        if(applyUid >0){
            cr.andApplyUidEqualTo(applyUid);
        }
        cr.andStatusEqualTo(status);
        if(productId > 0){
            cr.andProductIdEqualTo(productId);
        }
        return readAgentReviewDao.selectCount(ex);
    }

    @Override
    public AgentReviewDTO get(int reviewId, int applyPid, boolean isDetail) throws ServiceException {
        AgentReviewDTO dto = null;
        if(reviewId > 0){
            AgentReview review = readAgentReviewDao.selectByPrimaryKey(reviewId);
            if(review != null){
                dto = new AgentReviewDTO();
                BeanUtils.copyProperties(review,dto);
                if(isDetail){
                    try {
                        setExt(dto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }else if(applyPid > 0){
            AgentReview review = readAgentReviewDao.selectByApplyPid(applyPid);
            if(review != null){
                dto = new AgentReviewDTO();
                BeanUtils.copyProperties(review,dto);
                if(isDetail){
                    try {
                        setExt(dto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return dto;
    }
    @Transactional
    @Override
    public int updateImage(Map map) throws ServiceException {
        int ret = 0;
        int reviewId = StringUtil.getInt(map.get("reviewId"), 0);
        try {
            AgentReview review = readAgentReviewDao.selectByPrimaryKey(reviewId);
            if(review != null){
                String url = map.get("image").toString();
                if(StringUtil.containEmpty(url)){
                    return  ret;
                }
                String urls = "";
                if(!StringUtil.containEmpty(review.getUrls())){
                    urls = review.getUrls()+","+url;
                }else {
                    urls = url;
                }
                review.setUrls(urls);
                ret = writeAgentReviewDao.updateByPrimaryKeySelective(review);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}
